package com.jiazhong.servlet;

import com.jiazhong.dao.StudentDao;
import com.jiazhong.dao.impl.StudentDaoImpl;
import com.jiazhong.model.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Servlet处理功能实现步骤：
 * 1.获取客户端提交数据
 * 2.调用底层处理类，进行功能处理
 * 3.向客户端响应
 */
@WebServlet("/AddStudent.do")
public class AddStudentServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            /**
             * 1.获取客户端提交数据，从request请求对象中获取，客户端提交的参数
             * request.getParameter(“参数名”)，根据参数名获取参数值
             */
            request.setCharacterEncoding("utf-8");
            String stu_name=request.getParameter("stu_name");
            int stu_sex=Integer.parseInt(request.getParameter("stu_sex"));
            Date stu_birthday=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("stu_birthday"));
            int stu_age=Integer.parseInt(request.getParameter("stu_age"));
            String  stu_phone=request.getParameter("stu_phone");
            String  stu_address=request.getParameter("stu_address");
            System.out.println(stu_name+" "+stu_sex+" "+stu_age+" "+stu_phone+" "+stu_birthday+" "+stu_address);
            /**
             * 将获得的参数封装到student对象中
             * 原理：按钮（Dao类）中调用细节（impl），细节需要实体类（Student）来调用数据并设置数据
             */
            Student student=new Student();
            student.setStu_name(stu_name);
            student.setStu_sex(stu_sex);
            student.setStu_birthday(stu_birthday);
            student.setStu_age(stu_age);
            student.setStu_phone(stu_phone);
            student.setStu_address(stu_address);


            /**
             * 2.调用底层处理类，进行功能处理
             */
            //2.1创建底层处理类对象
            StudentDao studentDao=new StudentDaoImpl();
            //2.2调用处理方法
            studentDao.addStudent(student);

            /**
             * 3.向客户端响应(重定向)
             */
            response.sendRedirect("addStudentSuccess.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("addStudentFail.jsp");
        }
    }
}
